package com.wugh.fast.module.mapper;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wugh.fast.module.api.bo.BasePageQueryBO;
import com.wugh.fast.module.api.vo.PageQueryResultVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import tk.mybatis.mapper.annotation.RegisterMapper;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * @author 吴冠辉
 * @date 2018/1/24
 */
@RegisterMapper
public interface CommonMapper<T> extends Mapper<T>, EnhanceMapper<T>, FnEnhanceMapper<T> {
    /**
     * 批量插入数据,如果使用该方法需要使用在接口中覆盖引入
     * {@link tk.mybatis.mapper.common.special.InsertListMapper}(支持自增长) 或 {@link tk.mybatis.mapper.additional.insert.InsertListMapper}(支持自定义主键)
     *
     * @param recordList
     * @return
     */
    int insertList(List<? extends T> recordList);

    default <T> PageQueryResultVO<T> pageSelect(Supplier<List<T>> supplier, BasePageQueryBO pageQuery) {
        if (StringUtils.isNotBlank(pageQuery.getSortName())) {
            String sortOrder = StringUtils.isBlank(pageQuery.getSortOrder()) ? "" : pageQuery.getSortOrder();
            //优先处理单个排序
            PageHelper.orderBy(pageQuery.getSortName() + " " + sortOrder);
        } else if (CollectionUtils.isNotEmpty(pageQuery.getSortList())) {
            //在处理多字段排序
            String orderBy = pageQuery.getSortList().stream().collect(Collectors.joining(","));
            PageHelper.orderBy(orderBy);
        }
        if (Objects.equals(pageQuery.getPageNumber(), 0)) {
            List<T> list = supplier.get();
            return PageQueryResultVO.of(list, pageQuery);
        } else {
            Page<T> page = PageHelper.startPage(pageQuery.getPageNumber(), pageQuery.getPageSize());
            List<T> list = supplier.get();
            PageQueryResultVO<T> resultVO = PageQueryResultVO.of(list, pageQuery);
            resultVO.setTotal(page.getTotal());
            resultVO.setPageNumber(page.getPageNum());
            resultVO.setPageSize(page.getPageSize());
            resultVO.setPages(page.getPages());
            return resultVO;
        }
    }

    default <T> List<T> orderSelect(Supplier<List<T>> supplier, String orderBy) {
        if (StringUtils.isNotBlank(orderBy)) {
            //如果不为空,则利用PageHelper来排序
            PageHelper.orderBy(orderBy);
        }
        return supplier.get();
    }
}
